import driver.nxt.NXTController
import driver.Controller
import driver.events.BatteryEvent
import grails.converters.JSON
import driver.exceptions.InitException
import driver.exceptions.DestroyException

class HomeController {

  static ctrl

  def index = {
  }

  def connect = {
    if(ctrl){
      render "already connected"
    }
    else{
      try{
        ctrl = new NXTController()
        ctrl.init()
        render "connected to robot"
      }
      catch(e){
        ctrl = null
        response.setStatus(500)
        render "could not connect to robot"
      }
    }
  }

  def disconnect = {
    if(ctrl){
      try{
        ctrl.destroy()
        ctrl = null
        render "disconnected from robot"
      }
      catch(e){
        ctrl = null
        response.setStatus(500)
        render "could not disconnect from robot"
      }
    }
    else{
      response.setStatus(500)
      render "not connected"
    }
  }

  def action = {
    def actionToExecute = ctrl.getActionBySafeName(params.id)
    if(actionToExecute){
      actionToExecute.execute()
      render actionToExecute.getActionName() + " executed ok"
    }
    else{
      response.setStatus(500)
      render "could not execute action"
    }
  }

  def events_as_json = {
    if(ctrl){
      render ctrl.getEvents() as JSON
    }
    else{
      response.setStatus(500)
      render "cannot get events"
    }
  }

  def actions_as_json = {
    if(ctrl){
      render ctrl.getActions() as JSON
    }
    else{
      response.setStatus(500)
      render "cannot get actions"
    }

  }
}
